package com.trkj.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.jpa.LmbCousumableDAO;
import com.trkj.pojos.LmbConsumable;


@Service
@Transactional
public class LmbHCService {
	@Autowired
	private LmbCousumableDAO cousumableDAO;
	
	/**
	 * 生成实体表的编号
	 * @param name
	 * @param n
	 * @return
	 */
	public String getId(String name,String n){					
		if(n==null){
			n=name+"000001";
		}else{
			long x=Integer.parseInt(n.substring (name.length())) +1;
			if(x<10){
				n=name+"00000"+x;
			}else if(x>=10 && x<100){
				n=name+"0000"+x;
			}else if(x>=100 && x<1000){
				n=name+"000"+x;
			}else if(x>=1000 && x<10000){
				n=name+"00"+x;
			}else if(x>=10000 && x<100000){
				n=name+"0"+x;
			}else {
				n=name+x;
			}
		}
		System.out.println("生成的编号:"+n);
		return n;
	}
	
	/**
	 * 添加耗材
	 * @param consumable
	 */
	public void addCousumable(LmbConsumable consumable ){
		LmbConsumable consuma = new LmbConsumable();
		consuma.setCId(hcId());
		consuma.setCName(consumable.getCName());
		consuma.setCMorms(consumable.getCMorms());
		cousumableDAO.save(consuma);
	}
	
	public String hcId(){
		String name = "h";
		String n = cousumableDAO.findMaxID(name);
		String id=getId(name,n);
		return id;		
	}
	
	public Map<String,Object> queryAllLmbConsumable(int page,int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<LmbConsumable> list = cousumableDAO.findLmbConsumableByPage(pr);
		long total = cousumableDAO.findCountLmbConsumable();
		Map<String,Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", list);
		return map;		
	}
	
	public void editCousumable(LmbConsumable consumable){
		//找到该耗材
		LmbConsumable desc = cousumableDAO.findOne(consumable.getCId());
		copyCousumable(consumable,desc);
		//编辑
		cousumableDAO.save(consumable);
	}
	
	public LmbConsumable queryCousumableById(String id){
		return cousumableDAO.findOne(id);
	}
	
	private void copyCousumable(LmbConsumable src, LmbConsumable desc) {
		desc.setCId(src.getCId());
		desc.setCName(src.getCName());
		desc.setCMorms(src.getCMorms());
	}
	
	public Map<String,Object> queryLmbConsumableByCname(String cname,int page,int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<LmbConsumable> list = cousumableDAO.findLmbConsumableByCname(pr,cname);
		long total = cousumableDAO.findCountLmbConsumableByCname(cname);
		Map<String,Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", list);
		return map;		
	}
	
}
